/**
 * A universal widget for browsing the journalized data in a Hackystat 8 Sensorbase host.
 */
package org.hackystat.ui.sensordatabrowser.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.Window;

/**
 * This class provides a universal widget for browsing the journalized data in a Hackystat 8 
 * Sensorbase host.
 * @author David J. Nickles
 */
public class CompositeWidget implements EntryPoint {

  private HostPanels hostPanels;
  private ImageConsciousStackPanel compartments;
  private Session session;
  
  /**
   * This method loads the initial setup.
   */
  public void onModuleLoad() {
    initLayout();
    rpcVersion();
  }
  
  /**
   * This method creates and initializes the small gadget settings panel.
   */
  public void initLayout() {
    (this.session = new Session()).setCompositeWidget(this);
    this.compartments = new ImageConsciousStackPanel();
    /* First Stack Item: Host Settings */
    this.compartments.add(new HTML("<div id=\"hostSettingsSlot\"></div>"), 
      "<div id=\"hostStatusSlot\"></div>", true);
    /* Second Stack Item: User Settings */
    this.compartments.add(new HTML("<div id=\"userSettingsSlot\"></div>"), 
      "<div id=\"userStatusSlot\"></div>", true);
    /* Third Stack Item: Calendar Widget */
    this.compartments.add(new HTML("<div id=\"calendarSettingsSlot\"></div>"), 
      "<div id=\"calendarStatusSlot\"></div>", true);
    RootPanel.get("settings").add(this.compartments);
    this.hostPanels = new HostPanels(session);
  }
  
  /**
   * This method displays the passed version in the UI.
   * @param version a string containing the version number 
   */
  public void setVersion(String version) {
    Window.setTitle("Hackystat: SensorDataBrowser " + version);
    RootPanel.get("version").add(new HTML("<b>" + version + "</b>"));
  }
  
  /**
   * Check with the servlet to see if the host is valid.
   */
  public void rpcVersion() {
    RPCServiceFactory.getInstance().getService().version(new AsyncCallback() 
    {
      public void onSuccess(Object result) {
        setVersion((String) result);
      }
  
      public void onFailure(Throwable caught) {
        if (caught instanceof com.google.gwt.user.client.rpc.InvocationException) {
          session.log(RPCServiceFactory.PRCERRORNAME, "Cannot invoke version request on servlet.");
        } 
        else {
          session.log(RPCServiceFactory.PRCERRORNAME, caught.toString());
        }
      }
    });
  }
  
  /**
   * Shows the widget at the specified index.
   * @param index of the Widget to show.
   */
  public void showStack(int index) {
    this.compartments.showStack(index);
  }
}
